<template>
  <VPage>
    <VTable ref="tableRef" v-bind="tableOptins">
      <template #form="{ form }">
        <XForm
          :fieldList="fieldList"
          :formOption="optionsData"
          :formData="form"
        >
          <template #create_user="{ value, input }">
            <VCascader
              :model-value="value"
              @update:model-value="input"
              collapse-tags
              class="w-[200px]"
              placeholder="创建人"
            />
          </template>
        </XForm>
      </template>
      <template #toolbar_btns>
        <VActionBar :actions="actions" />
      </template>
      <template #entry_warehouse_time="{ row }">
        {{ formatTime(row?.entry_warehouse_time) }}
      </template>
      <template #matching_result_text="{ row }">
        <div class="flex items-center">
          <SvgIcon icon-class="SuccessFilled" v-if="row?.match_status == 1"/>
          <SvgIcon icon-class="HintFilled" v-if="row?.match_status == 2"/>
          <SvgIcon icon-class="CircleCloseFilled" v-if="row?.match_status == 3"/>
          {{ row?.match_result || "-" }}
        </div>
        <VText :value="row?.match_error_msg" :line="2"></VText>
      </template>
    </VTable>
    <BatchConfirm
      v-model="confirmVisible"
      :rows="selectRows"
      @close="selectRows = ''"
      @refresh="refresh"
    />
    <FreightDialog
      v-model="freightVisible"
      :id="select"
      :billsId="billsId"
      :data="selectInfo"
      @close="select = ''"
    />

    <SurchargeDialog
      v-model="surchargeVisible"
      :id="surchargeId"
      :data="surchargeInfo"
      :title="surchargeTitle"
      @close="(surchargeId = ''), (surchargeTitle = '')"
    />
    <BoxDialog
      v-model="boxVisible"
      :id="select"
      @close="select = ''"
      @refresh="refresh"
    />
    <add
      v-model="visible"
      :select="select"
      @close="select = ''"
      @refresh="refresh"
    />
    <DepDialog
      v-model="visibleDep"
      :data="depData"
      @close="depData = {}"
      @refresh="refresh"
    />
    <DerivedCenter ref="DerivedCenterRef"></DerivedCenter>
  </VPage>
</template>
<script setup lang="jsx">
import { ElMessage } from "element-plus";
import XForm from "@/components/XForm/index.vue";
import add from "./add/index.vue";
import DerivedCenter from "@/components/DerivedCenter/index.vue";
import { config_name } from "@/config/export.js";
import { getTableSelectRow, getTableSelect } from "@/hooks/tool.js";
import { useFetchSelect } from "@/hooks";
import BatchConfirm from "./components/BatchConfirm/index.vue";
import FreightDialog from "./components/FreightDialog/index.vue";
import SurchargeDialog from "./components/surchargeDialog/index.vue";
import BoxDialog from "./components/BoxDialog/index.vue";
import { formatTime } from "@/utils/time.js";
import { transportCostList, optsTcMainConfig } from "./api/index.js";
import DepDialog from "./components/depDialog/index";
import SvgIcon from "@/components/SvgIcon/index.vue";
const { proxy } = getCurrentInstance();
const route = useRoute();
const { options: optionsData } = useFetchSelect({
  params: ["finance.initial-bills-detail", "map.channel"],
});
const billsId = ref(null);
const bill_dts = ref(null);
onMounted(() => {
  const { id, _dts } = route.query;
  billsId.value = id;
  bill_dts.value = _dts;
});

const tableRef = ref();
const renderColumns = () => {
  return [
    { fixed: "left", width: 50, type: "checkbox" },
    {
      fixed: "left",
      width: 120,
      title: "入仓时间",
      field: "entry_warehouse_time",
      slots: { default: "entry_warehouse_time" },
    },
    {
      fixed: "left",
      title: "头程备库单号",
      minWidth: 160,
      field: "initial_backup_order_number",
    },
    {
      title: "月账单重量/周账单重量/差异重量(kg)",
      width: 300,
      slots: {
        header: ({ row }) => {
          return bill_dts.value
            ? "月账单重量/周账单重量/差异重量(kg)"
            : "账单重量/系统重量/差异重量(kg)";
        },
        default: ({ row }) => {
          const billWeight = bill_dts.value
            ? row?.diff_mw_dts?.month_bill_weight_kg
            : row?.bill_weight;
          const systemWeight = bill_dts.value
            ? row?.diff_mw_dts?.week_bill_weight_kg
            : row?.system_weight;
          const diffWeight = bill_dts.value
            ? row?.diff_mw_dts?.diff_mw_bill_weight_kg
            : row?.diff_weight;
          return (
            <div>
              <div class="flex">
                <span>{billWeight || 0} / </span>
                <span
                  class="ml-[4px] text-[#3487FF] cursor-pointer"
                  onClick={() => handleSysWeight(row.id)}
                >
                  {systemWeight || 0} /
                </span>
                <span class="ml-[4px] text-[#E50113]">{diffWeight || 0}</span>
              </div>
            </div>
          );
        },
      },
    },
    {
      title: "月账单单价 / 周账单单价 / 差异单价 (CNY)",
      width: 300,
      slots: {
        header: ({ row }) => {
          return bill_dts.value
            ? "月账单单价 / 周账单单价 / 差异单价 (CNY)"
            : "账单单价 / 系统单价 / 差异单价 (CNY)";
        },
        default: ({ row }) => {
          const billPrice = bill_dts.value
            ? row?.diff_mw_dts?.month_bill_unit_price_cny
            : row?.bill_unit_price;
          const systemPrice = bill_dts.value
            ? row?.diff_mw_dts?.week_bill_unit_price_cny
            : row?.system_unit_price;
          const diffPrice = bill_dts.value
            ? row?.diff_mw_dts?.diff_mw_bill_unit_price_cny
            : row?.diff_unit_price;
          return (
            <div>
              <div class="flex">
                <span>{billPrice || 0} / </span>
                <span class="ml-[4px]">{systemPrice || 0} / </span>
                <span class="ml-[4px] text-[#E50113]">{diffPrice || 0} </span>
              </div>
            </div>
          );
        },
      },
    },
    {
      title: "账单总额 / 系统总额 / 差异总额 (CNY)",
      width: 300,
      slots: {
        header: ({ row }) => {
          return bill_dts.value
            ? "月账单总额 / 周账单总额 / 差异总额 (CNY)"
            : "账单总额 / 系统总额 / 差异总额 (CNY)";
        },
        default: ({ row }) => {
          const billAmount = bill_dts.value
            ? row?.diff_mw_dts?.month_bill_amount_cny
            : row?.bill_amount;
          const systemAmount = bill_dts.value
            ? row?.diff_mw_dts?.week_bill_amount_cny
            : row?.system_amount;
          const diffAmount = bill_dts.value
            ? row?.diff_mw_dts?.diff_mw_bill_amount_cny
            : row?.diff_amount;
          return (
            <div>
              <div class="flex">
                <span>{billAmount || 0} / </span>
                <span class="ml-[4px]">{systemAmount || 0} / </span>
                <span class="ml-[4px] text-[#E50113]">{diffAmount || 0}</span>
              </div>
            </div>
          );
        },
      },
    },
    {
      title: "物流渠道\n物流单号\n分摊方式",
      width: 180,
      slots: {
        default: ({ row }) => {
          return (
            <div>
              <p>{row?.channel_name || "-"}</p>
              <p>{row?.tracking_number || "-"}</p>
              <p>{row?.allocation_method || "-"}</p>
            </div>
          );
        },
      },
    },
    {
      title: "国家\n目的仓\n计费类型",
      width: 200,
      field: "logistics_name",
      slots: {
        default: ({ row }) => {
          return (
            <div>
              <p>{row?.destination_country || "-"}</p>
              <VText value={row?.warehouse} line="1"></VText>
              <div>{row?.billing_type_text || "-"}</div>
            </div>
          );
        },
      },
    },
    {
      title: "数量及价格",
      width: 260,
      slots: {
        default: ({ row }) => {
          return (
            <div>
              <div class="flex">
                <div class="mr-[20px]  min-w-[80px]">
                  票数：{row?.vote_num || 0}
                </div>
                <div>件数：{row?.item_num || 0}</div>
              </div>
              <div class="flex">
                <div class="mr-[20px] min-w-[80px]">
                  数量：{row?.total_num || 0}
                </div>
                <div>单价：{row?.unit_price || 0}</div>
              </div>
            </div>
          );
        },
      },
    },
    { title: "币种", width: 100, field: "currency" },

    {
      title: "运费(CNY)",
      width: 200,
      field: "freight",
      slots: {
        default: ({ row }) => (
          <el-button
            text
            type="primary"
            onClick={() => handleFreightDetail({ id: row.id, row })}
          >
            {row.freight}
          </el-button>
        ),
      },
    },
    { title: "计费重平均差异", width: 150, field: "difference_avg_weight" },
    { title: "cost", width: 200 },
    { title: "合计金额", width: 200, field: "total_amount" },
    {
      title: "匹配结果",
      fixed: "right",
      width: 140,
      field: "matching_result_text",
      slots: { default: "matching_result_text" },
    },
    {
      title: "确认及备注",
      width: 200,
      fixed: "right",
      slots: {
        default: ({ row }) => {
          return (
            <div>
              <p>{row?.is_confirmed_text || "-"}</p>
              <VText title="备注" value={row?.remark || "-"} line={2} />
            </div>
          );
        },
      },
    },
    {
      title: "操作",
      width: 130,
      fixed: "right",
      slots: {
        default: ({ row }) => {
          return (
            <div>
              <el-button link type="primary" onClick={() => handleEdit(row)}>
                修改
              </el-button>
              {row.is_validity_nos == 0 ? (
                <el-button link type="primary" onClick={() => handleDep(row)}>
                  修改部门
                </el-button>
              ) : null}
            </div>
          );
        },
      },
    },
  ];
};
const tableOptins = reactive({
  formConfig: {
    data: {},
  },
  tooltipConfig: {
    showAll: false,
  },
  rowConfig: {
    height: 75,
  },
  isToggle: true,
  columns: renderColumns(),
  proxyConfig: {
    autoLoad: false, // 是否自动加载查询数据
    props: {
      result: "data",
      total: "total",
    },
    ajax: {
      query: async ({ page, form }) => {
        return handleReq(page, form);
      },
    },
  },
});
const tcMainCost = ref([]);
const getOptsTcFeeConfig = async () => {
  const { data } = await optsTcMainConfig();
  tcMainCost.value = data || [];
};
const handleReq = async (page, form) => {
  try {
    await getOptsTcFeeConfig();
    const res = await transportCostList({
      ...form,
      ...page,
      finance_initial_bills_id: billsId.value,
      _dts: bill_dts.value || undefined,
    });
    const { data = [] } = res || {};

    const _surchargeMap = tcMainCost.value.reduce(
      (acc, { label, value }) => {
        acc.labels.push(label);
        acc.identMap[label] = value;
        return acc;
      },
      { labels: [], identMap: {} }
    );

    const _body = data.map((item) => {
      const surcharges = item.aggregate_surcharge.reduce(
        (acc, { cost_ident, cost_value, cost_label }) => {
          acc[`surcharge${cost_ident}`] = cost_value;
          acc[`surcharge_id${cost_ident}`] = cost_ident;
          acc[`surcharge_label${cost_ident}`] = cost_label;
          return acc;
        },
        {}
      );
      return { ...item, ...surcharges };
    });
    let _columns = renderColumns();
    const costColumns = _surchargeMap.labels.map((label, index) => {
      const costIdent = _surchargeMap.identMap[label];
      return {
        title: label,
        field: `surcharge${costIdent}`,
        width: 200,
        slots: {
          default: ({ row }) => (
            <div>
              {row?.[`surcharge${costIdent}`] ? (
                <el-button
                  link
                  type="primary"
                  onClick={() =>
                    handleFee({
                      id: row[`surcharge_id${costIdent}`],
                      data: row,
                      title: row[`surcharge_label${costIdent}`],
                    })
                  }
                >
                  {row?.[`surcharge${costIdent}`]}
                </el-button>
              ) : (
                // <div>{row?.[`surcharge${costIdent}`]}</div>
                "-"
              )}
            </div>
          ),
        },
      };
    });

    if (costColumns.length > 0) {
      _columns = _columns
        .map((col) => {
          if (col.title === "cost") {
            return costColumns;
          }
          return col;
        })
        .flat();
    } else {
      _columns = _columns.filter((col) => col.title !== "cost");
    }
    tableRef.value.$table.loadColumn(_columns);
    return { data: _body, total: res.total };
  } catch (e) {
    console.error(e);
  }
};
const surchargeVisible = ref(false);
const surchargeTitle = ref("");
const surchargeId = ref(null);
const surchargeInfo = ref([]);
const handleFee = (data) => {
  surchargeInfo.value = data.data || [];
  surchargeId.value = data.id || null;
  surchargeTitle.value = data.title || null;
  surchargeVisible.value = true;
};
//编辑
const select = ref("");
const visible = ref(false);
const handleEdit = (_rows) => {
  select.value = _rows;
  visible.value = true;
};
//修改部门
const visibleDep = ref(false);
const depData = ref({});
const handleDep = (rows) => {
  depData.value = rows;
  visibleDep.value = true;
};
const freightVisible = ref(false);
const selectInfo = ref({});
const handleFreightDetail = (e) => {
  const { id: _id, row: _row } = e || {};
  freightVisible.value = true;
  selectInfo.value = _row;
  select.value = _id;
};
const boxVisible = ref(false);
const handleSysWeight = (_id) => {
  if (!_id) return;
  boxVisible.value = true;
  select.value = _id;
};

const DerivedCenterRef = ref();
const handleExport = async () => {
  let condition = getTableSelectRow(tableRef.value);
  DerivedCenterRef.value.open({
    tag_name: config_name["finance_manage"]["initial_bill_detail"],
    condition: { ...condition, finance_initial_bills_id: billsId.value },
  });
};
const confirmVisible = ref(false);
const selectRows = ref({});
const handleBatchConfirm = () => {
  const rows = getTableSelect(tableRef.value);
  if (!rows.length) return ElMessage.warning("请至少选择一条数据!");
  confirmVisible.value = true;
  selectRows.value = rows;
};
const refresh = () => {
  tableRef?.value.$table.commitProxy("query");
};

const actions = [
  {
    label: "批量确认及备注",
    type: "primary",
    fn: handleBatchConfirm,
  },
  { label: "导出", right: true, dkicon: "icon-Upload", fn: handleExport },
];
const publicStyle = { style: { width: "240px" } };
const fieldList = [
  {
    field: "no",
    placeholder: "请输入",
    select: [
      { label: "物流跟踪号", value: "tracking_number" },
      { label: "平台单号", value: "initial_backup_order_number" },
    ],
    type: "input",
    selectStyle: { width: "110px" },
    ...publicStyle,
  },
  {
    field: "channel_id",
    type: "select",
    originOption: "map.channel",
    ...publicStyle,
    options: {
      placeholder: "渠道名称",
      labelKey: "channel_name",
      valueKey: "channel_id",
    },
  },
  {
    field: "match_status",
    type: "select",
    options: {
      placeholder: "匹配结果",
    },
    originOption: "matching_result",
    ...publicStyle,
  },
];
</script>
